package com.example.seakdreamandroid.firstPage;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.FavoriteActivity;
import com.example.seakdreamandroid.Lullaby.LullabyActivity;
import com.example.seakdreamandroid.R;
import com.example.seakdreamandroid.WebViewActivity;
import com.example.seakdreamandroid.bedtimeStory.BedtimeStory;
import com.example.seakdreamandroid.bonus.BonusPointsActivity;
import com.example.seakdreamandroid.chatbot.ChatbotActivity;
import com.example.seakdreamandroid.crosstalk.Crosstalk;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.gentleMusic.GentleMusic;
import com.example.seakdreamandroid.recommendDay.RecommendDayActivity;
import com.example.seakdreamandroid.sleep.NapActivity;
import com.example.seakdreamandroid.sleep.RecordSleep;
import com.example.seakdreamandroid.whiteNoise.SleepFriendChannel;
import com.example.seakdreamandroid.whiteNoise.WhiteNoiseActivity;
import com.example.seakdreamandroid.questions.Question;
import com.example.seakdreamandroid.questions.Questions;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.BezierRadarHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.transformer.ZoomOutPageTransformer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/*主页*/

/**
 * 何鸿辉
 */
public class FirstPage extends Fragment {
    private SmartRefreshLayout sm;
    //轮播图控件
    private Banner banner;
    //轮播图的适配器
    private MyBannerAdapter bannerAdapter;
    private Activity activity;
    //字面意思
    private LinearLayout body;
    private ConcurrentHashMap<String, RecommendChannelView> channelViews = new ConcurrentHashMap<String,RecommendChannelView>();
    //摇篮曲
    private RelativeLayout LullabyRl;
    //ASMR
    private RelativeLayout AsmrRl;
    //戏曲
    private RelativeLayout operaRl;
    //冥想
    private RelativeLayout museRl;

    private RelativeLayout dailyButton;
    private RelativeLayout pointsButton;
    private RelativeLayout aiButton;
    //白噪音 杨锐涵
    private RelativeLayout whiteNoise;
    private RelativeLayout friendButton;

    private User user;

    //SmartRefreshLayout刷新和加载更多完成时发送消息在此处理
//    private Handler myHandler = new Handler(Looper.myLooper()){
//        @Override
//        public void handleMessage(@NonNull Message msg) {
//            super.handleMessage(msg);
//            //处理子线程发送的消息
//            switch(msg.what){
//                case REFRESH:
//                    //刷新，轮播图内容更新，推荐音频更新，文章刷新
//                    List<>
//                    bannerAdapter.setDatas();
//                    break;
//                case LOAD_MORE:
//                    //加载更多文章个，暂不实现
//                    break;
//            }
//        }
//    };


    //常量
    public static final String WHITE_NOISE = "白噪音";
    public static final String CROSS_TALK = "相声";
    public static final String BEDTIME_STORY = "睡前故事";
    public static final String OPERA = "戏曲";
    public static final String MUSE = "冥想";
    public static final String LULLABY= "摇篮曲";
    public static final String ASMR = "ASMR";
    public static final String LIGHT_MUSIT = "轻音乐";

    private final int REFRESH = 0;       //刷新
    private final int LOAD_MORE = 1;     //加载更多


    //创建fragment对应的视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        this.activity = getActivity();
        sm = (SmartRefreshLayout) inflater.inflate(R.layout.home_layout, container, false);
        user = (User) getActivity().getApplication();
        initView();
        initSmartRefreshLayout();
        initBanner();
        initChannel();
        initType();//设置摇篮曲，ASMR，戏曲，冥想学习界面的跳转--孔维鑫
        body.findViewById(R.id.record_sleep).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RecordSleep.class);
                startActivity(intent);
            }
        });
        refreshAllChannelData();
        return sm;
    }

    private void refreshAllChannelData() {
        for(RecommendChannelView channelView : channelViews.values()){
            refreshChannelData(channelView.getAudioType());
        }
    }

    private void refreshChannelData(String audioType) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL+"recommend/getRecommendData?userId" + user.getUserId() + "&type=" +audioType)
                .get()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                sm.finishRefresh();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                try {
                    String resultStr = response.body().string();
                    System.out.println("resultStr=" + resultStr);
                    JSONObject obj = new JSONObject(resultStr);
                    JSONArray array = obj.getJSONArray("data");
                    List<RecommendAudio> recommends = new ArrayList<RecommendAudio>();
                    if(array!=null){
                        for(int i = 0; i < array.length(); i++){
                            JSONObject audioTemp = array.getJSONObject(i);
                            RecommendAudio audio = new RecommendAudio();
                            audio.setTitle(audioTemp.getString("title"));
                            audio.setImageUrl(audioTemp.getString("imageUrl"));
                            audio.setTime(audioTemp.getString("time"));
                            audio.setWhite(audioTemp.getBoolean("white"));
                            if(audio.isWhite()){
                                audio.setWhiteId1(audioTemp.getString("whiteId1"));
                                audio.setWhiteId2(audioTemp.getString("whiteId2"));
                                audio.setWhiteId3(audioTemp.getString("whiteId3"));
                                audio.setWhiteName1(audioTemp.getString("whiteName1"));
                                audio.setWhiteName2(audioTemp.getString("whiteName2"));
                                audio.setWhiteName3(audioTemp.getString("whiteName3"));
                                audio.setWhiteImg1(audioTemp.getString("whiteImg1"));
                                audio.setWhiteImg2(audioTemp.getString("whiteImg2"));
                                audio.setWhiteImg3(audioTemp.getString("whiteImg3"));
                                audio.setWhiteUrl1(audioTemp.getString("whiteUrl1"));
                                audio.setWhiteUrl2(audioTemp.getString("whiteUrl2"));
                                audio.setWhiteUrl3(audioTemp.getString("whiteUrl3"));
                                audio.setWhiteCount(audioTemp.getInt("whiteCount"));
                            }else{
                                audio.setAudioId(audioTemp.getString("audioId"));
                                audio.setAudioUrl(audioTemp.getString("audioUrl"));
                            }
                            recommends.add(audio);
                            System.out.println("type=" + audioType + ",i="+i+",recommendAudio=" + audio);
                        }
                        RecommendChannelView channelView = channelViews.get(audioType);
                        RecommendAudioAdapter adapter = channelView.getAdapter();
                        System.out.println("hashCode="+adapter.hashCode());
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.setRecommendAudioList(recommends);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sm.finishRefresh();
            }
        });
    }


    //设置摇篮曲，ASMR，戏曲，冥想学习界面的跳转--孔维鑫
    private void initType() {
        LullabyRl = sm.findViewById(R.id.button_tolullaby);
        AsmrRl = sm.findViewById(R.id.button_toasmr);
        operaRl = sm.findViewById(R.id.button_toopera);
        museRl = sm.findViewById(R.id.button_tomuse);

        LullabyRl.setOnClickListener(new ClickIn());
        AsmrRl.setOnClickListener(new ClickIn());
        operaRl.setOnClickListener(new ClickIn());
        museRl.setOnClickListener(new ClickIn());


        whiteNoise = sm.findViewById(R.id.home_white_noise);
        whiteNoise.setOnClickListener(new ClickIn());

        dailyButton = sm.findViewById(R.id.daily_button);
        pointsButton = sm.findViewById(R.id.points_button);
        aiButton = sm.findViewById(R.id.ai_button);
        friendButton =  sm.findViewById(R.id.friend_button);
        dailyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), RecommendDayActivity.class);
                startActivity(intent);
            }
        });
        pointsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), BonusPointsActivity.class);
                startActivity(intent);
            }
        });
        aiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ChatbotActivity.class);
                startActivity(intent);
            }
        });
        friendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), NapActivity.class);
                startActivity(intent);
            }
        });
    }

    //为页面跳转设置监听器--孔维鑫
    public class ClickIn implements View.OnClickListener{

        @Override
        public void onClick (View v){

            switch (v.getId()){
                case R.id.button_tolullaby:
                    Intent intent = new Intent(getActivity(),Crosstalk.class);
                    startActivity(intent);
                    break;
                case R.id.button_toasmr:
                    Intent intent2 = new Intent(getActivity(),BedtimeStory.class);
                    startActivity(intent2);
                    break;
                case R.id.button_toopera:
                    Intent intent3 = new Intent(getActivity(),GentleMusic.class);
                    startActivity(intent3);
                    break;
                case R.id.button_tomuse:
                    Intent intent4 = new Intent(getActivity(), FavoriteActivity.class);
                    startActivity(intent4);
                    break;
                case R.id.home_white_noise:
                    Intent intent1 = new Intent(sm.getContext(), WhiteNoiseActivity.class);
                    startActivityForResult(intent1,1);


                    break;

            }
        }
    }



    private void initChannel() {
        List<String> config = getChannelConfig();
        for(String name:config){
            addAudioRecommend(name);
        }
    }

    private void initSmartRefreshLayout() {
        //设置刷新头
        sm.setRefreshHeader(new BezierRadarHeader(activity));
        sm.setRefreshFooter(new ClassicsFooter(activity));
        sm.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshAllChannelData();
            }
        });
        sm.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                sm.finishLoadMore();
            }
        });
    }

    private void initView() {
        body = sm.findViewById(R.id.body);
        banner = body.findViewById(R.id.banner);
    }

    private void addAudioRecommend(String audioType) {
        View v = LayoutInflater.from(activity).inflate(R.layout.recommend_audio_layout,null);
        body.addView(v);
        TextView more = v.findViewById(R.id.more);
        switch(audioType){
            case WHITE_NOISE:
                more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getContext(),WhiteNoiseActivity.class);
                        startActivity(intent);
                    }
                });
                break;
            case BEDTIME_STORY:
                more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getContext(),BedtimeStory.class);
                        startActivity(intent);
                    }
                });
                break;
            case LIGHT_MUSIT:
                more.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getContext(),GentleMusic.class);
                        startActivity(intent);
                    }
                });
                break;
        }
        RecommendChannelView channelView = new RecommendChannelView(audioType,v);
        channelView.getTitle().setText("精选"+audioType);
        RecyclerView recyclerView = channelView.getRecyclerView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        RecommendAudioAdapter adapter = new RecommendAudioAdapter(activity,new ArrayList<RecommendAudio>());
        recyclerView.setAdapter(adapter);
        System.out.println("hashCode:" + channelView.getV());
        System.out.println("hashCode:" + channelView.hashCode());
        System.out.println("hashCode:" + channelView.getRecyclerView().hashCode());
        System.out.println("hashCode:" + channelView.getAdapter().hashCode());
        channelViews.put(audioType,channelView);
    }

    private void initBanner() {
        banner.addPageTransformer(new ZoomOutPageTransformer());
        List<String> imageUrls = getBannerData();
        bannerAdapter = new MyBannerAdapter(imageUrls,activity);
        banner.addBannerLifecycleObserver(this)
                .setAdapter(bannerAdapter)
                .setIndicator(new CircleIndicator(activity));
        /**
         * 张清雅 为轮播图片添加点击事件
         */
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(Object data, int position) {
                if (data.equals("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBc2VhMTRSWGRjSDFnd3dkdTh3dTZmNElueGJOP2U9QUVub2tm.jpg")) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), Questions.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), WebViewActivity.class);
                    intent.putExtra("uri", (String) data);
                    startActivity(intent);
                }
            }
        });
        //设置指示器必须在条件指示器之后
        banner.setIndicatorSpace(20);
        banner.setIndicatorWidth(20,20);
        banner.setIndicatorHeight(20);
    }

    //读取本地配置信息，也就是喜欢的频道是什么
    private List<String> getChannelConfig() {
        List<String> result = new ArrayList<String>();
        //模拟读取本地配置
        result.add(WHITE_NOISE);
        return result;
    }
    /**
     * 张清雅 修改轮播图片
     * @return
     */
    //获取网络轮播图的信息
    private List<String> getBannerData(){
        List<String> result = new ArrayList<String>();
        //模拟从服务器获取轮播图的图片的url，起始还应该包括点击时候的处理方法等等，此处暂且忽略，到时候再改
//        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBc2VhMTRSWGRjSDFnd3dkdTh3dTZmNElueGJOP2U9QUVub2tm.jpg");
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBc2VhMTRSWGRjSDFndzFlYkR3VUdZbHFjODUzP2U9djlZdGRm.jpg");
        result.add("https://link.jscdn.cn/1drv/aHR0cHM6Ly8xZHJ2Lm1zL3UvcyFBc2VhMTRSWGRjSDFnd3Y0bk9oTUhTeXB2TlNNP2U9OWtSb3RF.jpg");
        return result;
    }
}